<?php defined('BASEPATH') OR exit('No direct script access allowed');

class members extends wsBackend
{

    public function index()
    {
        $data = array();

        $this->tpl->meta ['title'] = '用户管理 - ' . $this->config->item('site_name');
        $this->tpl->meta ['description'] = '';
        $this->tpl->meta ['keywords'] = '';
        $this->tpl->page_header = '用户管理';
        $this->tpl->breadcrumbs['Members'] = 'active';

        $data['status'] = $this->user_model->get_all_status();
        $data['user_types'] = $this->user_model->get_all_user_type();
        $data['order_by'] = array(
            'u.user_seq_id' => '用户ID',
            'u.user_email' => 'Email',
            'u.user_name' => '用户名',
            'u.user_status_seq_id' => '用户状态'
        );
        $data['order_type'] = array('desc' => 'Descending', 'asc' => 'Ascending');

        if ($this->input->get('user_name'))
            $filter['name'] = $this->input->get('user_name');
        if (isset($_GET['status']) && array_key_exists($this->input->get('status'), $data['status']))
            $filter['status'] = (int)$this->input->get('status');
        if ($this->input->get('access_type') && array_key_exists($this->input->get('access_type'), $data['user_types']))
            $filter['access_type'] = $this->input->get('access_type');
        if ($this->input->get('order_type') && array_key_exists($this->input->get('order_type'), $data['order_type']))
            $filter['order_type'] = $this->input->get('order_type');
        if ($this->input->get('order_by') && array_key_exists($this->input->get('order_by'), $data['order_by']))
            $filter['order_by'] = $this->input->get('order_by');


        $config['uri_segment'] = 4;
        $data['offset'] = $filter['offset'] = $this->uri->segment($config['uri_segment']);
        $config['base_url'] = preg_replace('/' . $this->config->item('url_suffix') . '$/ix', '', admin_url('members/index'));
        $config['per_page'] = $filter['per_page'] = $this->config->item('items_per_page');
        if (!empty($_GET)) {
            $get_method = '/?' . http_build_query($this->input->get());
            $config['suffix'] = $this->config->item('url_suffix') . $get_method;
            $config['first_url'] = $config['base_url'] . $get_method;
        } else {
            $config['suffix'] = $this->config->item('url_suffix');
        }
        $this->tpl->page_header_ = $config['total_rows'] = $this->user_model->users_count($filter);
        $config['use_page_numbers'] = FALSE;
        $this->load->library('pagination');
        $this->pagination->initialize($config);

        $data['pagination'] = $this->pagination->create_links();
        $data['users'] = $this->user_model->get_all_users($filter);


        $this->tpl->contents [] = $this->tpl->fetch('contents/members', $data);
        $this->tpl->render();
    }

    public function add()
    {
        $data = array();

        $this->tpl->meta ['title'] = '添加用户 - ' . $this->config->item('site_name');
        $this->tpl->meta ['description'] = '';
        $this->tpl->meta ['keywords'] = '';
        $this->tpl->page_header = '添加用户';
        $this->tpl->breadcrumbs['Members'] = admin_url('members');
        $this->tpl->breadcrumbs['Add'] = 'active';

        $data['status'] = $this->user_model->get_all_status();
        $data['user_types'] = $this->user_model->get_all_user_type();
        $data['user'] = false;

        $this->load->library('form_validation');
        $this->form_validation->set_rules('user_email', 'User Email', 'required|valid_email');

        if ($this->form_validation->run()) {
            $email = $this->input->post('user_email');
            $this->load->helper('string');
            $validate_exists = $this->user_model->get_userByEmail($email);
            if ($validate_exists) {
                $this->tpl->error[] = '邮箱已存在';
            } else {
                $insert_data = array(
                    'user_email' => $email,
                    'user_name' => ($this->input->post('user_name') ? $this->input->post('user_name') : NULL),
                    'user_password' => ws_password_hash(($this->input->post('user_password') ? $this->input->post('user_password') : random_string())),
                    'user_type_seq_id' => (array_key_exists($this->input->post('user_type_seq_id'), $data['user_types']) ? $this->input->post('user_type_seq_id') : 1),
                    'user_emailConfirm' => ($this->input->post('user_emailConfirm') ? TRUE : false),
                    'user_created' => date('Y-m-d H:i:s'),
                    'user_emailCode' => sha1(random_string()),
                    'user_status_seq_id' => (array_key_exists($this->input->post('user_status_seq_id'), $data['status']) ? $this->input->post('user_status_seq_id') : 1)
                );
                $user_id = $this->user_model->insert($insert_data);
                if ($user_id) {
                    $this->session->set_flashdata('SUCCESS', '创建成功');
                    $this->user->sendEmail($user_id);
                    redirect(admin_url('members'));
                } else {
                    $this->tpl->error[] = '无法将数据插入到数据库';
                }
            }
        }

        $this->tpl->contents [] = $this->tpl->fetch('contents/members_update', $data);
        $this->tpl->render();
    }

    public function delete($id, $offset = '')
    {
        $this->user_model->delete_userByID($id);
        $this->session->set_flashdata('SUCCESS', $id . '用户删除成功');
        redirect(admin_url('members/index/' . $offset));
    }

    public function edit($id, $offset = '')
    {
        $data = array();

        $this->tpl->meta ['title'] = '修改用户 ' . $id . ' - ' . $this->config->item('site_name');
        $this->tpl->meta ['description'] = '';
        $this->tpl->meta ['keywords'] = '';
        $this->tpl->page_header = '修改用户 - ' . $id;
        $this->tpl->breadcrumbs['Members'] = admin_url('members');
        $this->tpl->breadcrumbs['Edit - ' . $id] = 'active';

        $data['status'] = $this->user_model->get_all_status();
        $data['user_types'] = $this->user_model->get_all_user_type();

        $user = $data['user'] = $this->user_model->get_userById($id);
        if (!$user) {
            $this->session->set_flashdata('ERROR', $id . '用户不存在');
            redirect(admin_url('members/index/' . $offset));
        }

        $this->load->library('form_validation');
        $this->form_validation->set_rules('user_email', 'User Email', 'required|valid_email');

        if ($this->form_validation->run()) {
            $email = $this->input->post('user_email');
            $this->load->helper('string');
            $has_error = false;
            if ($email != $user->user_email) {
                $validate_exists = $this->user_model->get_userByEmail($email);
                if ($validate_exists) {
                    $this->tpl->error[] = '邮箱已存在';
                    $has_error = true;
                }
            }
            if (!$has_error) {
                $update_data = array(
                    'user_email' => $email,
                    'user_name' => ($this->input->post('user_name') ? $this->input->post('user_name') : NULL),
                    'user_type_seq_id' => (array_key_exists($this->input->post('user_type_seq_id'), $data['user_types']) ? $this->input->post('user_type_seq_id') : 1),
                    'user_emailConfirm' => ($this->input->post('user_emailConfirm') ? TRUE : false),
                    'user_status_seq_id' => (array_key_exists($this->input->post('user_status_seq_id'), $data['status']) ? $this->input->post('user_status_seq_id') : 1)
                );

                if ($this->input->post('user_password'))
                    $update_data['user_password'] = ws_password_hash($this->input->post('user_password'));
                if ($this->input->post('user_emailCode'))
                    $update_data['user_emailCode'] = sha1(random_string());

                $user_id = $this->user_model->update_user($update_data, array(
                    'user_seq_id' => $user->user_seq_id
                ));
                if ($user_id) {
                    $this->session->set_flashdata('SUCCESS', $user->user_email . '用户修改成功');
                    redirect(admin_url('members/index/' . $offset));
                } else {
                    $this->tpl->error[] = '无法将数据插入到数据库';
                }
            }
        }

        $this->tpl->contents [] = $this->tpl->fetch('contents/members_update', $data);
        $this->tpl->render();
    }

    public function delete_bulk($offset)
    {
        $post = $this->input->post('user_id');
        if ($post) {
            $this->user_model->delete_bulkUsers($post);
            $this->session->set_flashdata('SUCCESS', count($post) . '用户删除成功');
        } else {
            $this->session->set_flashdata('ERROR', '请通过单击复选框的选择用户');
        }
        redirect(admin_url('members/index/' . $offset));
    }
}
